package com.agrimall.service.impl;

import com.agrimall.entity.Banner;
import com.agrimall.mapper.BannerMapper;
import com.agrimall.service.BannerService;
import com.agrimall.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

/**
 * Banner轮播图服务实现类
 */
public class BannerServiceImpl implements BannerService {
    
    @Override
    public List<Banner> getVisibleBanners() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            BannerMapper mapper = sqlSession.getMapper(BannerMapper.class);
            return mapper.selectVisibleOrderBySort();
        } finally {
            sqlSession.close();
        }
    }
    
    @Override
    public Banner getBannerById(Long bannerId) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            BannerMapper mapper = sqlSession.getMapper(BannerMapper.class);
            return mapper.selectById(bannerId);
        } finally {
            sqlSession.close();
        }
    }
    
    @Override
    public boolean addBanner(Banner banner) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            BannerMapper mapper = sqlSession.getMapper(BannerMapper.class);
            int result = mapper.insert(banner);
            sqlSession.commit();
            return result > 0;
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            return false;
        } finally {
            sqlSession.close();
        }
    }
    
    @Override
    public boolean updateBanner(Banner banner) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            BannerMapper mapper = sqlSession.getMapper(BannerMapper.class);
            int result = mapper.update(banner);
            sqlSession.commit();
            return result > 0;
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            return false;
        } finally {
            sqlSession.close();
        }
    }
    
    @Override
    public boolean deleteBanner(Long bannerId) {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            BannerMapper mapper = sqlSession.getMapper(BannerMapper.class);
            int result = mapper.delete(bannerId);
            sqlSession.commit();
            return result > 0;
        } catch (Exception e) {
            sqlSession.rollback();
            e.printStackTrace();
            return false;
        } finally {
            sqlSession.close();
        }
    }
    
    @Override
    public List<Banner> getAllBanners() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try {
            BannerMapper mapper = sqlSession.getMapper(BannerMapper.class);
            return mapper.selectAll();
        } finally {
            sqlSession.close();
        }
    }
}



